package com.tzbank.bigdata.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tzbank.bigdata.dao.CommonipMapper;
import com.tzbank.bigdata.service.FtpCommonipService;
import com.tzbank.entity.bigdata.Commonip;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wangbin
 *2018-07-03
 *从大数据ftp服务器读取数据文件入库,常用IP
 */

@Slf4j
@Service(value = "ftpCommonipService")
@RefreshScope
public class FtpCommonipServiceImpl implements FtpCommonipService {
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private int type = 1;
	@Autowired
	private Environment environment;
	@Autowired
	private CommonipMapper commonipMapper;
	
	
	@Override
	public boolean downFile() {
		List<Commonip> batList = new ArrayList<Commonip>();
		String host = environment.getProperty("host", String.class);
		int port = environment.getProperty("port", Integer.class).intValue();
		String username = environment.getProperty("username", String.class);
		String password = environment.getProperty("password", String.class);
		String path = environment.getProperty("path", String.class);
		log.info("开始到大数据平台取常用IP数据文件：" + "host=" + host + ";username=" + username + ";port=" + port + ";path=" + path);
		String dateTime = dateFormat.format(new Date());
		String date = dateTime.substring(0, 10).replaceAll("-", "");
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			//连接并登陆ftp服务器
			ftp.connect(host, port);
			ftp.login(username, password);
			int replay = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(replay)) {
				log.info("登陆失败！");
				ftp.disconnect();
				return success;
			}
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			if (path != null && path.length() > 0) {
				String newPath = path + date + "/";
				//进入当天的数据文件目录
				ftp.changeWorkingDirectory(newPath);
				String fileName = "D60_MCJNL_COMMONIP_" + date + "_001.dat";
				ftp.enterLocalActiveMode();
				InputStream ins = ftp.retrieveFileStream(fileName);
				if(ins == null) {
					log.info("ftp服务器没有文件或者文件为空，文件路径："+newPath+";文件名："+fileName);
					return success;
				}
				BufferedReader reader = new BufferedReader(new InputStreamReader(ins, "UTF-8"));
				String inLine = reader.readLine();
				while (inLine != null) {
					String beanStr = inLine + System.getProperty("line.separator");
					char split = (char) Integer.parseInt("1E", 16);
					String str = String.valueOf(split);
					if (beanStr.indexOf(str) > 0) {
						String[] beanStrs = beanStr.split(str);
						Commonip bat = new Commonip();
						bat.setMchannelid(beanStrs[0]);
						bat.setCustomerno(beanStrs[1]);
						bat.setCountip(beanStrs[2]);
						bat.setCountip(beanStrs[3].replace("\r\n", ""));
						bat.setCreateDate(dateTime);
						bat.setUpdateDate(dateTime);
						log.info("beanStrs[0]=" + beanStrs[0] + "beanStrs[1]=" + beanStrs[1] + "beanStrs[2]="
								+ beanStrs[2] + "beanStrs[3]=" + beanStrs[3]);
						batList.add(bat);
						//批量入库操作，20条数据一批次
						if (batList.size() == 20) {
							this.batchInsert(batList);
							batList.clear();
						}
					}
					inLine = reader.readLine();
				}
				//当最后一批次不够20条数据时，执行此入库操作
				if (batList != null && batList.size() < 20) {
					this.batchInsert(batList);
				}
				//还原type值，下个跑批任务执行时，根据这个值先删除表数据再插入
				type = 1;
				reader.close();
				if (ins != null) {
					ins.close();
					// ftp.completePendingCommand();
				}
				ftp.logout();
				success = true;
				log.info("读取数据文件结束！");
			}
		} catch (Exception e) {
			log.info("从ftp读取数据文件失败", e);
			return success;
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException e) {
					log.info("关闭ftp连接失败", e);
				}
			}
		}
		return success;
	}

	/**
	 * 批量插入，每个批次开始时，先清空表数据，再插入
	 * @param list
	 */
	@Transactional
	private void batchInsert(List<Commonip> list) throws Exception{
		if (type == 1) {
			this.commonipMapper.deleteCommonip();
			type = 2;
		}
		this.commonipMapper.insertCommonip(list);
	}

}
